#!/bin/bash

# 南昌旅游系统 - 生产环境部署脚本（Linux）
# 使用方法: sudo bash deploy_production_complete.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}[错误] 请使用sudo运行此脚本${NC}"
    exit 1
fi

PROJECT_DIR=$(cd "$(dirname "$0")/.." && pwd)
cd "$PROJECT_DIR"

echo "========================================"
echo "  南昌旅游系统 - 生产环境部署脚本"
echo "========================================"
echo ""

# 1. 检查环境
echo -e "${GREEN}[1/10] 检查环境...${NC}"
command -v python3 >/dev/null 2>&1 || { echo -e "${RED}[错误] 未找到Python3${NC}"; exit 1; }
command -v node >/dev/null 2>&1 || { echo -e "${RED}[错误] 未找到Node.js${NC}"; exit 1; }
command -v mysql >/dev/null 2>&1 || { echo -e "${YELLOW}[警告] 未找到MySQL客户端${NC}"; }
command -v nginx >/dev/null 2>&1 || { echo -e "${YELLOW}[警告] 未找到Nginx${NC}"; }

# 2. 安装系统依赖
echo -e "${GREEN}[2/10] 安装系统依赖...${NC}"
if command -v apt-get >/dev/null 2>&1; then
    apt-get update
    apt-get install -y python3-pip python3-venv mysql-server redis-server nginx git
elif command -v yum >/dev/null 2>&1; then
    yum install -y python3-pip python3-venv mysql-server redis nginx git
fi

# 3. 配置后端环境
echo -e "${GREEN}[3/10] 配置后端环境...${NC}"
cd "$PROJECT_DIR/backend"

if [ ! -d "venv" ]; then
    python3 -m venv venv
fi

source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
pip install gunicorn python-dotenv

# 4. 创建.env文件
echo -e "${GREEN}[4/10] 创建环境配置文件...${NC}"
if [ ! -f ".env" ]; then
    SECRET_KEY=$(python3 -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())")
    cat > .env << EOF
DEBUG=False
SECRET_KEY=$SECRET_KEY
ALLOWED_HOSTS=*
DB_NAME=nanchang_tour
DB_USER=nanchang_user
DB_PASSWORD=your_password_123
DB_HOST=localhost
DB_PORT=3306
REDIS_URL=redis://127.0.0.1:6379/1
CELERY_BROKER_URL=redis://127.0.0.1:6379/0
CELERY_RESULT_BACKEND=redis://127.0.0.1:6379/0
EOF
    echo -e "${YELLOW}[提示] 请编辑 backend/.env 文件配置数据库连接信息${NC}"
fi

# 5. 数据库迁移
echo -e "${GREEN}[5/10] 数据库迁移...${NC}"
python manage.py migrate --noinput || echo -e "${YELLOW}[警告] 数据库迁移失败，请检查数据库配置${NC}"

# 6. 收集静态文件
echo -e "${GREEN}[6/10] 收集静态文件...${NC}"
mkdir -p staticfiles
python manage.py collectstatic --noinput || echo -e "${YELLOW}[警告] 静态文件收集失败${NC}"

# 7. 配置前端环境
echo -e "${GREEN}[7/10] 配置前端环境...${NC}"
cd "$PROJECT_DIR/frontend"
if [ ! -d "node_modules" ]; then
    npm install
fi

# 8. 构建前端
echo -e "${GREEN}[8/10] 构建前端生产版本...${NC}"
npm run build

# 9. 创建部署目录
echo -e "${GREEN}[9/10] 创建部署目录...${NC}"
DEPLOY_DIR="/opt/nanchang-tour"
mkdir -p "$DEPLOY_DIR/backend"
mkdir -p "$DEPLOY_DIR/frontend"
mkdir -p /var/log/nanchang-tour

# 复制文件
echo "复制后端文件..."
cp -r "$PROJECT_DIR/backend"/* "$DEPLOY_DIR/backend/" 2>/dev/null || true
rm -rf "$DEPLOY_DIR/backend/venv" "$DEPLOY_DIR/backend/__pycache__" 2>/dev/null || true

echo "复制前端文件..."
cp -r "$PROJECT_DIR/frontend/dist"/* "$DEPLOY_DIR/frontend/" 2>/dev/null || true

# 设置权限
chown -R www-data:www-data "$DEPLOY_DIR/frontend" 2>/dev/null || chown -R nginx:nginx "$DEPLOY_DIR/frontend" 2>/dev/null || true
chmod -R 755 "$DEPLOY_DIR"

# 10. 配置Nginx
echo -e "${GREEN}[10/10] 配置Nginx...${NC}"
cat > /etc/nginx/sites-available/nanchang-tour << 'NGINX_EOF'
server {
    listen 80;
    server_name _;  # 替换为实际域名

    # 前端
    location / {
        root /opt/nanchang-tour/frontend;
        try_files $uri $uri/ /index.html;
        index index.html;
    }

    # API代理
    location /api/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # 静态文件
    location /static/ {
        alias /opt/nanchang-tour/backend/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # 媒体文件
    location /media/ {
        alias /opt/nanchang-tour/backend/media/;
        expires 7d;
    }

    # 日志
    access_log /var/log/nginx/nanchang-tour-access.log;
    error_log /var/log/nginx/nanchang-tour-error.log;
}
NGINX_EOF

# 启用站点
ln -sf /etc/nginx/sites-available/nanchang-tour /etc/nginx/sites-enabled/
nginx -t && systemctl reload nginx || echo -e "${YELLOW}[警告] Nginx配置测试失败${NC}"

# 11. 创建systemd服务
echo -e "${GREEN}[11/10] 创建systemd服务...${NC}"
cat > /etc/systemd/system/nanchang-tour.service << 'SERVICE_EOF'
[Unit]
Description=Nanchang Tour Backend Service
After=network.target mysql.service redis.service

[Service]
Type=notify
User=www-data
Group=www-data
WorkingDirectory=/opt/nanchang-tour/backend
Environment="PATH=/opt/nanchang-tour/backend/venv/bin"
ExecStart=/opt/nanchang-tour/backend/venv/bin/gunicorn \
    --config /opt/nanchang-tour/backend/gunicorn_config.py \
    travel_plan.wsgi:application
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
SERVICE_EOF

systemctl daemon-reload
systemctl enable nanchang-tour.service || echo -e "${YELLOW}[警告] 服务启用失败${NC}"

echo ""
echo "========================================"
echo -e "${GREEN}  ✅ 部署完成！${NC}"
echo "========================================"
echo ""
echo "部署目录: $DEPLOY_DIR"
echo ""
echo "下一步操作:"
echo "1. 编辑 $DEPLOY_DIR/backend/.env 配置数据库"
echo "2. 运行: sudo systemctl start nanchang-tour"
echo "3. 检查服务: sudo systemctl status nanchang-tour"
echo "4. 查看日志: sudo journalctl -u nanchang-tour -f"
echo ""
echo "访问地址: http://$(hostname -I | awk '{print $1}')"
echo ""

